import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { formatMessage, FormattedMessage } from 'umi/locale';
import { Row, Table, Button, Form, Input, Modal, Alert, Select, Popconfirm } from 'antd';

const FormItem = Form.Item;
const { TextArea } = Input;

const ProductTopicForm = Form.create()(props => {
  const { modalVisible, form, detail, handleModalVisible, handleAdd } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      handleAdd(fieldsValue, form);
    });
  };

  return (
    <Modal
      title={formatMessage({ id: 'app.dm.product.topic.custom' })}
      destroyOnClose
      visible={modalVisible}
      width={618}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <div style={{ width: 530, paddingLeft: 44 }}>
        <Alert
          message={formatMessage({ id: 'app.dm.product.topic.custom.desc' })}
          type="info"
          showIcon
        />
        <FormItem>
          {form.getFieldDecorator('productId', { initialValue: detail.id })(
            <Input type="hidden" />,
          )}
        </FormItem>
        <FormItem label={formatMessage({ id: 'app.dm.product.topic.permission' })} colon={false}>
          {form.getFieldDecorator('handlePermission', {
            rules: [
              {
                required: true,
                message: formatMessage({ id: 'app.dm.product.topic.permission.place' }),
              },
            ],
            initialValue: 1,
          })(
            <Select style={{ width: 486 }}>
              <Select.Option value={1}>
                {formatMessage({ id: 'app.dm.product.topic.permission.publish' })}
              </Select.Option>
              <Select.Option value={2}>
                {formatMessage({ id: 'app.dm.product.topic.permission.subscribe' })}
              </Select.Option>
              <Select.Option value={3}>
                {formatMessage({ id: 'app.dm.product.topic.permission.publishsubscribe' })}
              </Select.Option>
            </Select>,
          )}
        </FormItem>
        <FormItem
          label={formatMessage({ id: 'app.dm.product.topic.permission.topicclass' })}
          colon={false}
        >
          {form.getFieldDecorator('topic', {
            rules: [
              {
                required: true,
                message: formatMessage({ id: 'app.dm.product.topic.permission.topicclass.place' }),
              },
            ],
          })(
            <Input
              placeholder={formatMessage({
                id: 'app.dm.product.topic.permission.topicclass.place',
              })}
            />,
          )}
        </FormItem>
        <FormItem
          label={formatMessage({ id: 'app.dm.product.topic.permission.desc' })}
          colon={false}
        >
          {form.getFieldDecorator(
            'desc',
            {},
          )(
            <TextArea
              style={{ width: 486 }}
              rows={4}
              placeholder={formatMessage({ id: 'app.dm.product.topic.permission.desc.place' })}
            />,
          )}
        </FormItem>
      </div>
    </Modal>
  );
});

@connect(({ product, loading }) => ({
  product,
  loading: loading.models.product,
}))
class ProductTopic extends PureComponent {
  state = {
    modalVisible: false,
  };

  columns = [
    {
      key: 'topicClass',
      dataIndex: 'topic',
      title: formatMessage({ id: 'app.dm.product.topic.table.topicclass' }),
    },
    {
      key: 'handlePermission',
      title: formatMessage({ id: 'app.dm.product.topic.table.permission' }),
      dataIndex: 'handlePermission',
      render: (text, record) => {
        if (record.handlePermission === 1) {
          return formatMessage({ id: 'app.dm.product.topic.permission.publish' });
        }
        if (record.handlePermission === 2) {
          return formatMessage({ id: 'app.dm.product.topic.permission.subscribe' });
        }
        if (record.handlePermission === 3) {
          return formatMessage({ id: 'app.dm.product.topic.permission.publishsubscribe' });
        }
        return null;
      },
    },
    {
      key: 'desc',
      title: formatMessage({ id: 'app.dm.product.topic.table.desc' }),
      dataIndex: 'desc',
    },
    {
      key: 'action',
      title: formatMessage({ id: 'app.dm.product.topic.table.action' }),
      render: (text, record) => {
        if (record.isSys === false) {
          return (
            <Popconfirm
              title={
                <div style={{ width: 280 }}>
                  <div
                    style={{
                      fontWeight: 'bold',
                      color: '000',
                      marginBottom: 10,
                      wordWrap: 'break-word',
                    }}
                  >
                    <span>
                      {formatMessage(
                        { id: 'app.dm.product.topic.del.confirm' },
                        { topic: record.topic },
                      )}
                    </span>
                  </div>
                </div>
              }
              onConfirm={() => this.handleDelete(record.id, record.productId)}
            >
              <a>
                <FormattedMessage id="app.dm.product.topic.table.action.del" />
              </a>
            </Popconfirm>
          );
        }
        return null;
      },
    },
  ];

  componentDidMount() {
    const {
      dispatch,
      product: { detail },
    } = this.props;

    dispatch({
      type: 'product/topics',
      payload: detail.id,
    });
  }

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleAdd = (fields, form) => {
    const { dispatch } = this.props;
    const { handleModalVisible } = this;
    dispatch({
      type: 'product/addTopic',
      payload: {
        ...fields,
      },
      form,
      handleModalVisible,
    });
  };

  handleDelete = (id, productId) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'product/delTopic',
      payload: {
        id,
        productId,
      },
    });
  };

  render() {
    const {
      product: { detail, topics },
    } = this.props;

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
      detail,
    };

    const { modalVisible } = this.state;

    return (
      <Fragment>
        <Row style={{ textAlign: 'right' }}>
          <Button type="primary" onClick={() => this.handleModalVisible(true)}>
            <FormattedMessage id="app.dm.product.topic.custom" />
          </Button>
        </Row>
        <Row style={{ marginTop: 15 }}>
          <Table columns={this.columns} dataSource={topics} pagination={false} rowKey="id" />
        </Row>
        <ProductTopicForm {...parentMethods} modalVisible={modalVisible} />
      </Fragment>
    );
  }
}

export default ProductTopic;
